//
//  HMComposetextView.swift
//  微博
//
//  Created by 程双岐 on 16/9/28.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

class HMComposetextView: UITextView {

    private lazy var placeHolderLabel: UILabel = {
       let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.text = "哈哈哈哈"
        label.textColor = UIColor.lightGray
        label.numberOfLines = 0
        return label
    }()
    var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    override var font: UIFont?{
        didSet{
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    override var text: String?{
        didSet{
            placeHolderLabel.isHidden = hasText
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        
        addSubview(placeHolderLabel)
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    }

    
    @objc private func textChange(){
        placeHolderLabel.isHidden = hasText
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}
